/*
 * @Author: fantasy 
 * @Date: 2021-11-22 10:58:39 
 * @Last Modified by: fantasy
 * @Last Modified time: 2021-11-22 16:35:16
 * 拖拽test
 */
import 'package:flutter/material.dart';

class DragDemo extends StatefulWidget {
  const DragDemo({Key key}) : super(key: key);

  @override
  _DragDemoState createState() => _DragDemoState();
}

class _DragDemoState extends State<DragDemo> {
  final colors = [
    Colors.red[100],
    Colors.red[200],
    Colors.red[300],
    Colors.red[400],
    Colors.red[500],
    Colors.red[600],
    Colors.red[700],
  ];

  //当前拖拽的index
  int _currentDragIndex = 0;

  final _globalKey = GlobalKey();

  double stackX = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DragDemo'),
        elevation: 0.0,
        centerTitle: true,
      ),
      backgroundColor: Colors.white,
      body: Center(
        child: Listener(
            onPointerMove: (event) {
              // print(event);
              final x = event.position.dx - stackX;
              if (x > (_currentDragIndex + 1) * Box.width) {
                if (_currentDragIndex == colors.length - 1) return;
                print(_currentDragIndex);
                setState(() {
                  final c = colors[_currentDragIndex];
                  colors[_currentDragIndex] = colors[_currentDragIndex + 1];
                  colors[_currentDragIndex + 1] = c;
                  _currentDragIndex++;
                });
              } else if (x < _currentDragIndex * Box.width) {
                if (_currentDragIndex == 0) return;
                setState(() {
                  final c = colors[_currentDragIndex];
                  colors[_currentDragIndex] = colors[_currentDragIndex - 1];
                  colors[_currentDragIndex - 1] = c;
                  _currentDragIndex--;
                });
              }
            },
            child: SizedBox(
                width: 400,
                child: Stack(
                    key: _globalKey,
                    children: List.generate(colors.length, (index) {
                      return Box(
                        key: ValueKey(colors[index]),
                        color: colors[index],
                        x: 50.0 * index,
                        y: 150,
                        onDrag: (color) {
                          //计算出stack的x
                          final renderBox = _globalKey.currentContext
                              .findRenderObject() as RenderBox;
                          print(renderBox.size.width);
                          stackX = renderBox.localToGlobal(Offset.zero).dx;
                          print(stackX);

                          //当前拖拽的颜色
                          final di = colors.indexOf(color);
                          _currentDragIndex = di;
                        },
                        onEnd: (_) {
                          // 对所有Box的颜色进行亮度取值，色值越深亮度越低
                          List<double> lightNums = colors.map((e) {
                            return e.computeLuminance();
                          }).toList();
                          print('lightNums == $lightNums');
                          bool isWin = true; //是否完成排序
                          //从大到小排序,亮度值依次减小
                          for (var i = 0; i < lightNums.length - 1; i++) {
                            //若出现小于后面的情况则未完成排序，跳出当前循环
                            if (lightNums[i] < lightNums[i + 1]) {
                              isWin = false;
                              break;
                            }
                          }
                          print(isWin ? 'win' : '');
                        },
                      );
                    })))),
      ),
    );
  }
}

class Box extends StatelessWidget {
  static const width = 50.0;
  static const height = 150.0;
  static const margin = 2.0;

  final Color color;
  final double x, y;
  final Function(Color) onDrag;
  final Function onEnd;

  const Box({Key key, this.color, this.x, this.y, this.onDrag, this.onEnd})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    final box = Container(
      width: width - margin * 2,
      height: height - margin * 2,
      decoration: BoxDecoration(
          color: color, borderRadius: BorderRadius.circular(10.0)),
    );

    return AnimatedPositioned(
        left: x,
        top: y,
        duration: Duration(milliseconds: 800),
        child: Draggable(
          onDragEnd: onEnd,
          onDragStarted: () => onDrag(color),
          child: box,
          childWhenDragging: Visibility(child: box, visible: false),
          feedback: box,
        ));
  }
}
